
import { resolve } from 'path'
import vue from '@vitejs/plugin-vue'
import { loadEnv } from 'vite'
import type { UserConfig, ConfigEnv } from 'vite'
import Components from 'unplugin-vue-components/vite';
import { AntDesignVueResolver } from 'unplugin-vue-components/resolvers';
import { createHtmlPlugin } from "vite-plugin-html";
import UnoCSS from 'unocss/vite'
import PurgeIcons from 'vite-plugin-purge-icons'

const root = process.cwd()

const pathResolve = (dir: string) => {
  return resolve(root, '.', dir)
}

export default ({ command, mode }: ConfigEnv): UserConfig => {
  let env = null;
  const isBuild = command === 'build';
  if (!isBuild) {
    env = loadEnv((process.argv[3] === "--mode" ? process.argv[4] : process.argv[3]), root)
  } else {
    env = loadEnv(mode, root)
  }
  return {
    base: env.VITE_BASE_PATH,
    plugins: [
      vue(),
      Components({
        resolvers: [AntDesignVueResolver({
          importStyle: false
        })],
        dts: false
      }),
      createHtmlPlugin({
        inject: {
          data: {
            title: env.VITE_APP_TITLE,
            injectScript: `<script src="./inject.js"></script>`
          }
        }
      }),
      UnoCSS(),
      PurgeIcons()
    ],
    css:{
      preprocessorOptions:{
        scss:{
          additionalData: '@import "@/styles/vars.scss";'
        }
      }
    },
    resolve: {
      extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.less', '.css', '.scss'],
      alias: {
        '@': resolve('src')
      }
    },
    server: {
      port: 2333,
      hmr: {
        overlay: false
      },
      host: '0.0.0.0'
    },
    optimizeDeps: {
      include: [
        'vue',
        'vue-router',
        'axios',
        'qs'
      ]
    },
    build: {
      minify: 'terser', // 压缩方式
      outDir: env.VITE_OUT_DIR || "dist", // 输出目录（打包后文件夹名称）
      sourcemap: env.VITE_SOURCEMAP === 'true' ? 'inline' : false, // 是否生成 sourcemap 文件
      terserOptions: {
        compress: {
          drop_debugger: env.VITE_DROP_DEBUGGER === 'true',
          drop_console: env.VITE_DROP_CONSOLE === 'true'
        }
      }
    }
  }
}
